#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: middlewared
# BEFORE: fsck earlykld
# KEYWORD: shutdown

. /etc/rc.subr

: ${middlewared_debug="NO"}
: ${middlewared_overlay_dirs=""}
pidfile=/var/run/middlewared.pid
daemon_pidfile=/var/run/middlewared_daemon.pid
command="/usr/sbin/daemon"

middlewared_start() {
	mount -uw /  # FIXME: why root is not rw by default?
	if ! mount | grep -q 'on /dev/fd (' 2> /dev/null; then
		mount -t fdescfs fdescfs /dev/fd
	fi
	overlay_dirs_arg=""
	for o in ${middlewared_overlay_dirs}; do
		overlay_dirs_arg="${overlay_dirs_arg} -o ${o}"
	done
	/sbin/ifconfig lo0 127.0.0.1 up
	if checkyesno middlewared_debug; then
		/usr/local/bin/tmux new-session -s middlewared -d
		/usr/local/bin/tmux send -t middlewared "env PATH=$PATH:/usr/local/sbin:/usr/local/bin LC_ALL=en_US.UTF-8 /usr/local/bin/middlewared ${overlay_dirs_arg} -P" ENTER
	else
		env PATH=$PATH:/usr/local/sbin:/usr/local/bin LC_ALL=en_US.UTF-8 ${command} -f -P ${daemon_pidfile} -p ${pidfile} -r /usr/local/bin/middlewared ${overlay_dirs_arg} --log-handler=file
	fi
	if ! LD_LIBRARY_PATH=/usr/local/lib /usr/local/bin/midclt -t 240 waitready; then
		echo "##############################################################"
		echo "MIDDLEWARED FAILED TO START, SYSTEM WILL NOT BEHAVE CORRECTLY!"
		echo "##############################################################"
	fi
}

middlewared_stop() {
	if [ -f "${pidfile}" ] ; then
		mw_pid=$(cat $pidfile)
		if [ -f "${daemon_pidfile}" ] ; then
			rc_pid=$(cat $daemon_pidfile)
		else
			rc_pid=$mw_pid
		fi
		echo 'Stopping middlewared.'
		kill -s TERM ${rc_pid}
		wait_for_pids ${mw_pid}
	else
		echo 'middlewared is not running'
		exit 1
	fi

	if checkyesno middlewared_debug; then
		/usr/local/bin/tmux kill-session -t 'middlewared'
	fi

	if [ -f "${pidfile}" ] ; then
		rm $pidfile
	fi
}

middlewared_status() {
	if [ -f "${pidfile}" ] ; then
		mw_pid=$(cat $pidfile)
		kill -0 "${mw_pid}" >> /dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo "$name is running as pid $mw_pid"
			return 0
		fi
	fi
	echo "$name is not running"
	return 1
}

name="middlewared"
start_cmd='middlewared_start'
status_cmd='middlewared_status'
stop_cmd='middlewared_stop'

load_rc_config $name
run_rc_command $*
